package com.hopu.day6_springboot.service.impl;

import com.hopu.day6_springboot.dao.UserDAO;
import com.hopu.day6_springboot.entity.User;
import com.hopu.day6_springboot.service.UserService;
import com.hopu.day6_springboot.service.UserService2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.sql.SQLException;

/**
 * 用户业务逻辑实现
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDAO userDAO;

    @Autowired
    private UserService2 userService2;

    @Transactional
    @Override
    public User login(String username, String password) throws SQLException {
        //调用dao对象进行登录
        return userDAO.login(username,password);
    }

    @Transactional(isolation = Isolation.REPEATABLE_READ)
    @Override
    public void transferPoint(Integer fromId, Integer toId, Integer pointer) {
        User user1 = userDAO.selectUserById(fromId);
        User user2 = userDAO.selectUserById(toId);
        user1.setPoint(user1.getPoint() - pointer);
        userDAO.updatePoint(user1);
//        int x = 1 / 0;
        user2.setPoint(user2.getPoint() + pointer);
        userDAO.updatePoint(user2);
    }

    @Transactional(propagation = Propagation.REQUIRED)
    @Override
    public void addPoint(Integer id, Integer point) {
        userService2.subtractPoint(id, 700);
        User user = userDAO.selectUserById(id);
        user.setPoint(user.getPoint() + point);
        userDAO.updatePoint(user);
        throw new RuntimeException("test error!!!!");
    }

}
